import type {RouteLocationNormalized, RouteRecordRaw} from "vue-router";
import {isNavigationFailure, Router} from "vue-router";
import {useUserStoreWidthOut} from "@/store/modules/user";
import {useAsyncRouteStoreWidthOut} from "@/store/modules/asyncRoute";
import tokenApi, { setToken } from "@/api/tokenApi";
import {SlashAppContext} from "@";
import {ErrorPageRoute} from "@/router/base";


const InsideOpenTempRouter: Map<string, string> = new Map();

const checkAddFirstOpen = (to: RouteLocationNormalized) => {
  if (to.query["slashInnerOpen"] != null) {
    return (("/" != to.path) && InsideOpenTempRouter.get(to.path) == undefined) || !to.path.startsWith("/navigation");
  } else {
    return false;
  }
};

function getTokenByUrl(query:any) {
  console.log('监测token', query);
  const time = Date.now() + 24 * 60 * 60 * 1000;
  if (Reflect.has(query, 'token')) {
    setToken(Reflect.get(query, 'token'), time);
  }
}
export function createRouterGuards(router: Router) {
  const userStore = useUserStoreWidthOut();
  const asyncRouteStore = useAsyncRouteStoreWidthOut();
  router.beforeEach(async (to, _form, next) => {
    console.log("路由跳转至",to.path)
    await SlashAppContext.isRouterReady(to.path);
    let route = router.getRoutes().filter(it => it.path === to.path);
    if (route.length == 0 && to.path.startsWith("/navigation")) {
      route = router.getRoutes().filter(it => it.path === to.path.replace("/navigation", ""));
    }
    //校验是否第一次打开
    if ((checkAddFirstOpen(to)) && route.length > 0) {
      const newPath = "/navigation" + route[0].path;
      const meta = {...to.meta};
      if (to.query["slashInnerTitle"]) {
        meta.title = to.query["slashInnerTitle"];
      }

      const r: RouteRecordRaw = {
        path: newPath,
        components: route[0].components,
        meta: meta
      } as unknown as RouteRecordRaw;
      router.addRoute("navigation", r);
      InsideOpenTempRouter.set(newPath, "xx");
      if (to.path.startsWith("/navigation")) {
        next();
      } else {
        await router.replace({path: newPath, query: to.query, params: to.params});
      }

    } else {
      next();
    }
  });
  router.beforeEach(async (to, from, next) => {
    //  next();
    //  console.log('wwwww',to);
    // console.log("来源路由:",from)
    const Loading = window["$loading"] || null;
    Loading && Loading.start();
    console.log(SlashAppContext.getAppConfig().loginPath);
    if (to.path === SlashAppContext.getAppConfig().loginPath || to.name === "errorPage") {
      next();
      return;
    }
    if (from.path === SlashAppContext.getAppConfig().loginPath && to.name === "errorPage") {
      //next(PageEnum.BASE_HOME);
      next();
      return;
    }
    // Whitelist can be directly entered
    if ([...SlashAppContext.getAppConfig().loginPath].includes(to.path)) {
      next();
      return;
    }

    /**通过url获取token */
    getTokenByUrl(to.query as any)
    //  const token = storage.get(ACCESS_TOKEN);
    const token = tokenApi.getToken();
    if (!token) {
      console.log(to);
      // You can access without permissions. You need to set the routing meta.ignoreAuth to true
      if (to.meta.ignoreAuth) {
        next();
        return;
      }
      // redirect login page
      const redirectData: { path: string; replace: boolean; query?: Recordable<string> } = {
        path: SlashAppContext.getAppConfig().loginPath,
        replace: true
      };
      if (to.path) {
        redirectData.query = {
          ...redirectData.query,
          redirect: to.path
        };
      }
      next(redirectData);
      return;
    }

    if (asyncRouteStore.getIsDynamicAddedRoute) {
      next();
      return;
    }
    const userInfo = await userStore.GetInfo();

    const routes = await asyncRouteStore.generateRoutes(userInfo);
    console.log(routes);

    // // 动态添加可访问路由表
    // routes.forEach((item) => {
    //   router.addRoute(item as unknown as RouteRecordRaw);
    // });

    //添加404
    const isErrorPage = router.getRoutes().findIndex((item) => item.name === ErrorPageRoute.name);
    if (isErrorPage === -1) {
      router.addRoute(ErrorPageRoute as unknown as RouteRecordRaw);
    }
    const redirectPath = (from.query.redirect || to.path) as string;
    const redirect = decodeURIComponent(redirectPath);
    const nextData = to.path === redirect ? {...to, replace: true} : {path: redirect};
    asyncRouteStore.setDynamicAddedRoute(true);
    next(nextData);
    Loading && Loading.finish();
  });

  router.afterEach((to, _form, failure) => {
    SlashAppContext.setFromPath(_form);
    document.title = (to?.meta?.title as string) || document.title;
    if (isNavigationFailure(failure)) {
      //console.log('failed navigation', failure)
    }
    const asyncRouteStore = useAsyncRouteStoreWidthOut();
    // 在这里设置需要缓存的组件名称
    const keepAliveComponents = asyncRouteStore.keepAliveComponents;
    const currentComName: any = to.matched.find((item) => item.name == to.name)?.name;
    if (currentComName && !keepAliveComponents.includes(currentComName) && to.meta?.keepAlive) {
      // 需要缓存的组件
      keepAliveComponents.push(currentComName);
    } else if (!to.meta?.keepAlive || to.name == "Redirect") {
      // 不需要缓存的组件
      const index = asyncRouteStore.keepAliveComponents.findIndex((name) => name == currentComName);
      if (index != -1) {
        keepAliveComponents.splice(index, 1);
      }
    }
    asyncRouteStore.setKeepAliveComponents(keepAliveComponents);
    const Loading = window["$loading"] || null;
    Loading && Loading.finish();
  });

  router.onError((error) => {
    console.log(error, "路由错误");
  });
}
